﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace seo_tool.lib
{
    class Shoulu
    {
        struct Item
        {
            public string url;
            public string title;
            public string is_shuolu;
            public int suoyin;
            public string is_run;
            public string search;
        };

        IWebDriver driver;
        string search;
        Sqlite conn;
        DataGridView dataGridViewData;
        RichTextBox richTextBoxInfo;
        

        public Shoulu(string search, Sqlite conn, DataGridView dataGridViewData, RichTextBox richTextBoxInfo)
        {
            this.search = search;
            this.conn = conn;
            this.dataGridViewData = dataGridViewData;
            this.richTextBoxInfo = richTextBoxInfo;
        }

        public void Start()
        {
            var chromeDriverService = ChromeDriverService.CreateDefaultService();
            chromeDriverService.HideCommandPromptWindow = true;

            ChromeOptions options = new ChromeOptions();
            //var proxy = new Proxy();
            //proxy.Kind = ProxyKind.Manual;
            //proxy.IsAutoDetect = false;
            //proxy.HttpProxy = "localhost:8080";
            //proxy.SslProxy = "localhost:8080";
            //options.Proxy = proxy;
            options.AddArgument(string.Format("--user-agent={0}", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"));
            options.AddArguments("--ignore-certificate-errors");
            options.AddArguments("--ignore-ssl-errors");
            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--hide-scrollbars");
            options.AddArgument("--incognito");
            options.AddArgument("--disable-web-security");
            options.AddArgument("--no-sandbox");
            options.AddArgument("lang=zh_CN.UTF-8");
            options.AddExcludedArgument("enable-automation");
            options.AddAdditionalCapability("useAutomationExtension", false);
            options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);//禁用图片
            options.AddArgument("disable-blink-features=AutomationControlled");

            string url = null;
            switch (search)
            {
                case "百度PC":
                    url = "https://www.baidu.com/";
                    break;
                case "搜狗PC":
                    url = "https://www.sogou.com/";
                    break;
                case "百度M":
                    url = "https://m.baidu.com/";
                    break;
                case "搜狗M":
                    url = "https://m.sogou.com/";
                    break;
                case "神马M":
                    url = "https://m.sm.cn/";
                    break;
            }
            if (search == "百度M" || search == "搜狗M" || search == "神马M")
            {
                ChromeMobileEmulationDeviceSettings CMEDS = new ChromeMobileEmulationDeviceSettings();
                CMEDS.Width = 436; //设置窗体显示宽高
                CMEDS.Height = 687;
                CMEDS.PixelRatio = 1.0;
                CMEDS.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25";
                options.EnableMobileEmulation(CMEDS);
            }
            driver = new ChromeDriver(chromeDriverService, options);
            driver.Navigate().GoToUrl(url);
        }

        public void Run()
        {
            Start();
            EchoInfo("chromedriver已开启！");
            Item item;
            for (int i = 0; i < dataGridViewData.Rows.Count - 1; i++)
            {
                string url = dataGridViewData.Rows[i].Cells["url"].Value.ToString();
                string title = dataGridViewData.Rows[i].Cells["title"].Value.ToString();
                EchoInfo("开始执行：" + url);
                if (title == "")
                {
                    title = GetTitle(url);
                    EchoInfo("获取标题：" + title);
                }
                else
                {
                    EchoInfo("跳过标题");
                }

                if (search == "百度PC")
                {
                    item = Baidu(url, title);
                }
                else if (search == "搜狗PC")
                {
                    item = Sougou(url, title);
                }
                else if (search == "百度M")
                {
                    item = BaiduM(url, title);
                }
                else if (search == "搜狗M")
                {
                    item = SougouM(url, title);
                }
                else if (search == "神马M")
                {
                    item = ShenmaM(url, title);
                }
                else
                {
                    Close();
                    EchoInfo("search错误");
                    return;
                }

                conn.update($"update shoulu set title = '{item.title}', is_shoulu = '{item.is_shuolu}', suoyin = {item.suoyin}, is_run = '{item.is_run}', search = '{item.search}' where url = '{item.url}'");
                dataGridViewData.Rows[i].Cells["title"].Value = item.title;
                dataGridViewData.Rows[i].Cells["is_shoulu"].Value = item.is_shuolu;
                dataGridViewData.Rows[i].Cells["suoyin"].Value = item.suoyin;
                dataGridViewData.Rows[i].Cells["is_run"].Value = item.is_run;
                dataGridViewData.Rows[i].Cells["search"].Value = item.search;
                EchoInfo("ok");

            }
            Close();
            EchoInfo("chromedriver已关闭！");
        }

        private Item Baidu(string url, string title)
        {
            Item item = new Item();
            item.url = url;
            item.title = title;
            item.is_shuolu = "";
            item.suoyin = 0;
            item.is_run = "已执行";
            item.search = "百度PC";

            driver.FindElement(By.XPath(".//input[@id='kw']")).Clear();
            driver.FindElement(By.XPath(".//input[@id='kw']")).SendKeys(url);
            driver.FindElement(By.XPath(".//input[@id='su']")).Click();
            Thread.Sleep(2000);
            string biaoshi = driver.FindElement(By.XPath(".//div[@id='content_left']/div")).GetAttribute("class");
            if (biaoshi == "result-molecule  new-pmd" || biaoshi == "result-molecule hit-toptip new-pmd")
            {
                item.is_shuolu = "未收录";
            }
            else
            {
                item.is_shuolu = "收录";
                driver.FindElement(By.XPath(".//input[@id='kw']")).Clear();
                driver.FindElement(By.XPath(".//input[@id='kw']")).SendKeys(title);
                driver.FindElement(By.XPath(".//input[@id='su']")).Click();
                Thread.Sleep(2000);
                int suoyin = BaiduSy(url, title);
                item.suoyin = suoyin;
            }

            return item;
        }

        private int BaiduSy(string url, string title)
        {
            var elements = driver.FindElements(By.XPath(".//div[@id='content_left']/div/h3/a"));
            string str;
            int i = 0;
            foreach (var element in elements)
            {
                i++;
                str = element.Text.Replace("...", "");
                if (title.Contains(str))
                {
                    Console.WriteLine(str);
                    element.Click();
                    Thread.Sleep(2000);
                    driver.SwitchTo().Window(driver.WindowHandles[1]);
                    Console.WriteLine(driver.Url);
                    if (driver.Url == url)
                    {
                        driver.Close();
                        driver.SwitchTo().Window(driver.WindowHandles[0]);
                        return i;
                    }
                    driver.Close();
                    driver.SwitchTo().Window(driver.WindowHandles[0]);
                }
            }
            return 0;
        }

        private Item Sougou(string url, string title)
        {
            Item item = new Item();
            item.url = url;
            item.title = title;
            item.is_shuolu = "";
            item.suoyin = 0;
            item.is_run = "已执行";
            item.search = "搜狗PC";

            try
            {
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(OpenQA.Selenium.Keys.LeftControl + "a");
                Thread.Sleep(500);
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(OpenQA.Selenium.Keys.Delete);
                Thread.Sleep(500);
                driver.FindElement(By.XPath(".//input[@id='upquery']")).SendKeys(url);
                driver.FindElement(By.XPath(".//input[@id='searchBtn']")).Click();
            }
            catch
            {
                driver.FindElement(By.XPath(".//input[@id='query']")).Clear();
                driver.FindElement(By.XPath(".//input[@id='query']")).SendKeys(url);
                driver.FindElement(By.XPath(".//input[@id='stb']")).Click();
            }
            Thread.Sleep(2000);
            string biaoshi = driver.FindElement(By.XPath(".//p[@class='num-tips']")).Text;
            if (biaoshi == "搜狗已为您找到约0条相关结果")
            {
                item.is_shuolu = "收录";
            }
            else
            {
                item.is_shuolu = "未收录";
            }

            return item;
        }

        private Item BaiduM(string url, string title)
        {
            Item item = new Item();
            item.url = url;
            item.title = title;
            item.is_shuolu = "";
            item.suoyin = 0;
            item.is_run = "已执行";
            item.search = "百度M";
            return item;
        }

        private Item SougouM(string url, string title)
        {
            Item item = new Item();
            item.url = url;
            item.title = title;
            item.is_shuolu = "";
            item.suoyin = 0;
            item.is_run = "已执行";
            item.search = "搜狗M";
            return item;
        }

        private Item ShenmaM(string url, string title)
        {
            Item item = new Item();
            item.url = url;
            item.title = title;
            item.is_shuolu = "";
            item.suoyin = 0;
            item.is_run = "已执行";
            item.search = "神马M";

            driver.FindElement(By.XPath(".//textarea[@id='kw']")).Clear();
            driver.FindElement(By.XPath(".//textarea[@id='kw']")).SendKeys(url);
            driver.FindElement(By.XPath(".//div[@class='btn submit']")).Click();
            Thread.Sleep(2000222);

            return item;
        }

        private string GetTitle(string Url, string postDataStr = "")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string html = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            string pattern = @"(?si)<title(?:\s+(?:""[^""]*""|'[^']*'|[^""'>])*)?>(?<title>.*?)</title>";
            string title = Regex.Match(html, pattern).Groups["title"].Value.Trim();
            return title;
        }

        public void Close()
        {
            driver.Close();
            driver.Quit();
            driver.Dispose();
        }

        private void EchoInfo(string info)
        {
            richTextBoxInfo.Text += info + "\r\n";
            richTextBoxInfo.SelectionStart = richTextBoxInfo.Text.Length;
            richTextBoxInfo.ScrollToCaret();
            richTextBoxInfo.Refresh();
        }

        ~Shoulu()
        {
            driver.Close();
            driver.Quit();
            driver.Dispose();
        }

    }
}
